<template>
  <body>
    <div class="login-container">
      <el-card class="login-card">
        <el-form
          :model="form"
          label-width="auto"
        >
          <el-form-item label="用户名:">
            <el-input v-model="form.UserName" />
          </el-form-item>
          <el-form-item label="密码:">
            <el-input v-model="form.Password" type="password" />
          </el-form-item>
          <!-- 验证码 -->
          <el-form-item label="验证码">
            <el-input v-model="form.captchaInput" style="width: 150px; margin-right: 10px;" placeholder="请输入验证码" />
            <canvas ref="captchaCanvas" @click="refreshCaptcha" style="cursor: pointer; vertical-align: middle;"></canvas>
          </el-form-item>
          <el-form-item style="margin-left: 58px">
            <el-button type="primary" @click="onSubmit">登录</el-button>
            <!-- <el-button>Cancel</el-button> -->
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </body>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";
import {useCounterStore} from '@/stores/counter';
const apiUrl = import.meta.env.VITE_APP_API_URL;
console.log(123, import.meta.env, apiUrl); // 打印环境变量

let curIdentifyCode = ref("");

const store = useCounterStore();

const router = useRouter();

const form = reactive({
  UserName: "",
  Password: "",
  captchaInput: "",
});

// 标记验证码是否验证通过
const isCaptchaVerified = ref(false);

// 引用 canvas 元素
const captchaCanvas = ref<HTMLCanvasElement | null>(null);

// 存储当前验证码
const currentCaptcha = ref('');

// 生成随机验证码
const generateCaptcha = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let captcha = '';
  for (let i = 0; i < 4; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    captcha += characters.charAt(randomIndex);
  }
  currentCaptcha.value = captcha;
  return captcha;
};

// 绘制验证码到 canvas 上
const drawCaptcha = (captcha: string) => {
  if (captchaCanvas.value) {
    const ctx = captchaCanvas.value.getContext('2d');
    if (ctx) {
      const width = captchaCanvas.value.width;
      const height = captchaCanvas.value.height;

      // 清空 canvas
      ctx.clearRect(0, 0, width, height);

      // 设置背景颜色
      ctx.fillStyle = '#f4f4f4';
      ctx.fillRect(0, 0, width, height);

      // 设置字体样式，将字体大小改为 50px
      ctx.font = '50px "Comic Sans MS", cursive, sans-serif';
      ctx.textBaseline = 'middle';
      ctx.textAlign = 'center';

      // 绘制验证码字符，每个字符使用不同颜色
      const colors = ['#FF5733', '#33FF57', '#5733FF', '#FF33E6'];
      const charWidth = width / captcha.length;
      for (let i = 0; i < captcha.length; i++) {
        const char = captcha[i];
        const x = i * charWidth + charWidth / 2;
        const y = height / 2;
        ctx.fillStyle = colors[i % colors.length];
        ctx.save();
        ctx.translate(x, y);
        ctx.rotate((Math.random() - 0.5) * 0.2);
        ctx.fillText(char, 0, 0);
        ctx.restore();
      }

      // 添加干扰线
      for (let i = 0; i < 3; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * width, Math.random() * height);
        ctx.lineTo(Math.random() * width, Math.random() * height);
        ctx.strokeStyle = '#999';
        ctx.lineWidth = 1;
        ctx.setLineDash([5, 15]);
        ctx.stroke();
      }

      //添加干扰点
      for (let i = 0; i < 20; i++) {
        const x = Math.random() * width;
        const y = Math.random() * height;
        ctx.beginPath();
        ctx.arc(x, y, 1, 0, 2 * Math.PI);
        ctx.fillStyle = '#999';
        ctx.fill();
      }
    }
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  const newCaptcha = generateCaptcha();
  drawCaptcha(newCaptcha);
  form.captchaInput = '';
  isCaptchaVerified.value = false;
};

// 页面加载时生成并绘制验证码
onMounted(() => {
  if (captchaCanvas.value) {
    const captcha = generateCaptcha();
    drawCaptcha(captcha);
  }
});

const onSubmit = () => {
  if (form.UserName === "" || form.Password === "") {
    ElMessage.error("请输入用户名和密码");
    return;
  }

  // 将用户输入的验证码和生成的验证码都转换为小写后再进行比较111
  if (form.captchaInput.toLowerCase()!== currentCaptcha.value.toLowerCase()) {
    ElMessage.error("验证码输入错误");
    return;
  }
  axios.get(apiUrl+"/T5/ProductInfo/LoginHandle", {
    params: {
      UserName: form.UserName,
      Password: form.Password
    }
  }).then((res) => {
          // 登录成功，写JWT的 token到本地
       window.localStorage.setItem("token", res.data.token);
        // 数据提交后端要加入新的Token值
        axios.defaults.headers.common["Authorization"] = res.data.token;
    console.log(res.data.token,"2222222");
    if (res.data.code === 202) {
      console.log(res.data.data[0].userName,"4444")
      ElMessage.success("登录成功");

      store.ccstore.UserName =res.data.data[0].userName
      store.ccstore.Password = res.data.password
      store.ccstore.captchaInput = res.data.captchaInput
      router.push('/MathEMS');
    } else {
      ElMessage.error("用户名或密码错误");
    }
  });
};
</script>

<style scoped>
body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
}

.login-container {
  text-align: center;
}

.login-card {
  width: 550px;
  padding: 50px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.code-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  margin-left: 10px;
}

canvas {
  border: 1px solid #ccc;
  cursor: pointer;
  width: 150px;
  height: 40px;
  border-radius: 4px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
</style>